<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
class Game_IndexController extends Core_Controller_Action_Standard
{
  protected $_navigation;

  public function init()
  {
    if( !$this->_helper->requireAuth()->setAuthParams('game', null, 'view')->isValid() ) return;
    
    if( !Engine_Api::_()->core()->hasSubject() )
    {
      if( 0 !== ($game_id = (int) $this->_getParam('game_id')) &&
          null !== ($game = Engine_Api::_()->getItem('game', $game_id)) )
      {
        Engine_Api::_()->core()->setSubject($game);
      }
      else if( 0 !== ($user_id = (int) $this->_getParam('user_id')) &&
          null !== ($user = Engine_Api::_()->getItem('user', $user_id)) )
      {
        Engine_Api::_()->core()->setSubject($user);
      }
    }
    
    $this->_helper->requireUser->addActionRequires(array(
      'manage',
    	'favorites',
    	'create'
    ));
  }
  
  
  public function indexAction()
  {
    $this->_helper->content->setNoRender()->setEnabled();
  }
  
  // NONE USER SPECIFIC METHODS
  public function browseAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->form = $form = new Game_Form_Filter_Browse();

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }
    
    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    $this->view->formValues = $values;
            
    $this->view->assign($values);

    if (!empty($values['user']))
    {
      $this->view->userObject = Engine_Api::_()->user()->getUser($values['user']);
    }    
    
    if (!empty($values['tag']))
    {
      $this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
    }    
    
    if (!empty($values['category']))
    {
      $this->view->categoryObject = Engine_Api::_()->game()->getCategory($values['category']);  
    }
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('game.perpage', 20);
    
    $values['search'] = 1;
    $values['status'] = Game_Model_Game::STATUS_PUBLISHED;
    
    $this->view->paginator = $paginator = Engine_Api::_()->game()->getGamesPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    
    
    // Render
    $this->_helper->content
      //  ->setNoRender()
        ->setEnabled()
        ;  
  }

  public function manageAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->form = $form = new Game_Form_Filter_Browse();

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }
    
    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    $this->view->formValues = $values;
            
    $this->view->assign($values);

    if (!empty($values['tag']))
    {
      $this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
    }    
    
    if (!empty($values['category']))
    {
      $this->view->categoryObject = Engine_Api::_()->game()->getCategory($values['category']);  
    }
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('game.perpage', 20);
    $values['user'] = $viewer;
 
    
    $this->view->paginator = $paginator = Engine_Api::_()->game()->getGamesPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    

    // Render
    $this->_helper->content
      //  ->setNoRender()
        ->setEnabled()
        ;  
  }
  // manage
  
  public function favoritesAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->form = $form = new Game_Form_Filter_Browse();

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }
    
    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    $this->view->formValues = $values;
            
    $this->view->assign($values);

    if (!empty($values['tag']))
    {
      $this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
    }    
    
    if (!empty($values['category']))
    {
      $this->view->categoryObject = Engine_Api::_()->game()->getCategory($values['category']);  
    }
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('game.perpage', 20);
    $values['favorite_user_id'] = $viewer->getIdentity();
    
    $values['search'] = 1;
    $values['status'] = Game_Model_Game::STATUS_PUBLISHED;    
    
    $this->view->paginator = $paginator = Engine_Api::_()->game()->getGamesPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    

    // Render
    $this->_helper->content
      //  ->setNoRender()
        ->setEnabled()
        ;  
  }
  // favorites
  
  public function createAction()
  {
    if( !$this->_helper->requireAuth()->setAuthParams('game', null, 'create')->isValid()) return;
    
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->_loadNavigations();
    
    $this->view->quota = $quota = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'game', 'max');
    $this->view->current_count = Engine_Api::_()->game()->countGames(array('user'=>$viewer));

    $this->view->form = $form = new Game_Form_Game_Create();
    
    if (!$this->getRequest()->isPost())
    {
      return;
    }
    
    if (!$form->isValid($this->getRequest()->getPost()))
    {
      return;
    }

    $values = $form->getValues();

    $table = Engine_Api::_()->getItemTable('game');
    $db = $table->getAdapter();
    $db->beginTransaction();

    try
    {     

      $values['user_id'] = $viewer->getIdentity();
      $values['distributor_type'] = 'Manual';

      $values['status'] = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'game', 'published') 
      	? Game_Model_Game::STATUS_PUBLISHED
      	: Game_Model_Game::STATUS_PENDING;
      
      
      $game = $table->createRow();
      $game->setFromArray($values);
      $game->save();

      
      // Add tags
      $tags = preg_split('/[,]+/', $values['keywords']);
      $tags = array_filter(array_map("trim", $tags));
      $game->tags()->addTagMaps($viewer, $tags);

      $customfieldform = $form->getSubForm('fields');
      $customfieldform->setItem($game);
      $customfieldform->saveValues();

      if (!empty($values['photo']) ) 
      {
        $game->setPhoto($form->photo);
      }      
      if (!empty($values['swf_file'])) {
        $game->setSwf($form->swf_file);
      }    

      // CREATE AUTH STUFF HERE
      $auth = Engine_Api::_()->authorization()->context;  
      $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

      $auth_keys = array(
        'view' => 'everyone',
        'comment' => 'registered',
      );
      
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
        
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($game, $role, $auth_key, ($i <= $authMax));
        }
      }

      // Add activity
      $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $game, 'game_new');
      if ($action != null)
      {
        Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $game);
      }

      // Commit
      $db->commit();
      
      //$this->_redirectCustom($game->getActionHref('upload'));
      //$this->_redirectCustom(array('route' => 'game_specific', 'action' => 'success', 'game_id' => $game->getIdentity()));
      return $this->_redirectCustom($game);
    }

    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }

  }

  
  public function tagsAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    
    $max = 100;
    $order = 'text';
    
    $params = array(
      'max' => 100,
      'order' => 'text',
      'search' => 1,
      'status' => Game_Model_Game::STATUS_PUBLISHED,
    );
    
    $this->view->tags = $tags = Engine_Api::_()->game()->getPopularTags($params);
    // Render
    $this->_helper->content
      //  ->setNoRender()
        ->setEnabled()
        ;  
  }

  protected function _loadNavigations()
  {
    // Get navigation
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_main');

    // Get quick navigation
    $this->view->quickNavigation = $quickNavigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_quick');    
  }
  
  
}

